<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="searchOptions.dorm_num" placeholder="宿舍号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-select v-model="searchOptions.dorm_id" placeholder="区号" clearable style="width: 90px" class="filter-item">
        <el-option v-for="item in dormitoryOptions" :key="item" :label="item" :value="item" />
      </el-select>

      <el-select v-model="searchOptions.sex" placeholder="性别" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in sex" :key="item" :label="item" :value="item" />
      </el-select>

      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>

      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>

      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      stripe
      @sort-change="sortChange"
    >
      <el-table-column label="序号" type="index" align="center" width="80" />
      <el-table-column label="区号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.dormitoryId }}区</span>
        </template>
      </el-table-column>
      <el-table-column label="栋号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.bannerId }}栋</span>
        </template>
      </el-table-column>

      <el-table-column label="性别" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag v-if="row.sex==0" color="#f89898" style="color: rgb(255, 255, 255);border: none;">
            女
          </el-tag>
          <el-tag v-else-if="row.sex==1" color="#79bbff" style="color: rgb(255, 255, 255);border: none;">
            男
          </el-tag>
          <el-tag v-else-if="row.sex==2" color="#b1b3b8" style="color: rgb(255, 255, 255);border: none;">
            未知
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="开始时间" class-name="status-col">
        <template slot-scope="{row}">
          <span>{{ row.beginTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="结束时间" class-name="status-col">
        <template slot-scope="{row}">
          <span>{{ row.endTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="区号" prop="dormitoryId">
          <el-input v-model="temp.dormitoryId" />
        </el-form-item>
        <el-form-item label="栋号" prop="bannerId">
          <el-input v-model="temp.bannerId" />
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select v-model="temp.sex" class="filter-item" placeholder="请选择性别">
            <el-option v-for="item in sex" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="开始时间" prop="beginTime">
          <el-select v-model="temp.beginTime" class="filter-item" placeholder="请选择开始时间">
            <el-option v-for="item in times" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-select v-model="temp.endTime" class="filter-item" placeholder="请选择结束时间">
            <el-option v-for="item in times" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchDorm, createDorm, updateDorm, deleteDorm } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import { MessageBox } from 'element-ui'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination

// arr to obj, such as { CN : "China", US : "USA" }

function compare(property, property2) {
  return function(a, b) {
    var value1 = a[property]
    var value2 = b[property]
    if (value1 !== value2) {
      return value1 - value2
    }
    return a[property2] - b[property2]
  }
}

export default {
  name: 'Dormmanager',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      times: ['1:00', '2:00', '3:00', '4:00', '5:00', '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '24:00'],
      ori_data: null,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        failureType: '无法上网',
        year: '2023',
        month: '05',
        status_order: '',
        staff_id: '20002',
        order_id: '202305041400516462835875'
      },
      searchOptions: {
        dorm_num: '',
        dorm_id: '',
        sex: ''
      },
      dormitoryOptions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
      sex: ['男', '女'],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['male', 'female', 'unkonw'],
      showReviewer: false,
      temp: {
        dormitoryId: '',
        bannerId: '',
        sex: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        dormitoryId: [{ required: true, message: '必填', trigger: 'change' }],
        bannerId: [{ required: true, message: '必填', trigger: 'change' }],
        sex: [{ required: true, message: '必填', trigger: 'blur' }],
        beginTime: [{ required: true, message: '必填', trigger: 'blur' }],
        endTime: [{ required: true, message: '必填', trigger: 'blur' }]

      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchDorm().then(response => {
        // console.log(response)
        this.ori_data = response.data.data
        this.ori_data.sort(compare('dormitoryId', 'bannerId'))

        this.list = this.ori_data
        // this.list.sort(compare('bannerId'))
        // this.total = 47
        // this.list = [{
        //   'dormitory_id': '1区',
        //   'banner_id': '2栋',
        //   'sex': 0,
        //   'begin_time': '12:00',
        //   'end_time': '16:00' }]

        // console.log(this.list)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.6 * 1000)
      })
    },
    handleFilter() {
      const dorm_num = this.searchOptions.dorm_num
      const dorm_id = this.searchOptions.dorm_id
      let sex = this.searchOptions.sex

      let id_qu = ''
      let id_dong = ''

      if (dorm_num.length > 5) {
        id_qu = dorm_num.slice(0, 2)
        id_dong = dorm_num.slice(2, 3)
      } else {
        id_qu = dorm_num.slice(0, 1)
        id_dong = dorm_num.slice(1, 2)
      }
      // console.log(id_qu, id_dong)

      let result = this.ori_data

      if (dorm_num !== '') {
        if (id_dong === '') {
          result = result.filter(item => {
            return String(item.dormitoryId) === id_qu
          })
        } else {
          result = result.filter(item => {
            return String(item.dormitoryId) === id_qu && String(item.bannerId) === id_dong
          })
        }
      }
      // console.log(result)

      if (dorm_id !== '') {
        result = result.filter(item => {
          return item.dormitoryId === dorm_id
        })
      }

      if (sex !== '') {
        if (sex === '女') {
          sex = 0
        } else if (sex === '男') {
          sex = 1
        } else {
          sex = 2
        }

        result = result.filter(item => {
          return item.sex === sex
        })
      }

      this.list = result
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        dormitoryId: '',
        bannerId: '',
        sex: ''
      }
    },

    handleCreate() {
      // console.log('hello')
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.sex = tempData.sex === '女' ? 0 : tempData.sex === '男' ? 1 : 2

          createDorm(tempData).then(() => {
            this.list.unshift(tempData)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp.ID = row.id
      this.temp.dormitoryId = row.dormitoryId
      this.temp.bannerId = row.bannerId
      this.temp.sex = row.sex === 0 ? '女' : row.sex === 1 ? '男' : '未知'

      // this.temp = Object.assign({}, row) // copy obj
      // this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.sex = tempData.sex === '女' ? 0 : tempData.sex === '男' ? 1 : 2
          // console.log(tempData)
          // tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateDorm(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === tempData.ID)
            this.list.splice(index, 1, tempData)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            })
          })
          // location.reload()
        }
      })
    },
    handleDelete(row, index) {
      MessageBox.confirm('您将要删除该宿舍,是否确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var data = {}
        data.dormitoryId = row.dormitoryId
        data.bannerId = row.bannerId
        deleteDorm(row)
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['区号', '栋号', '性别', '开始时间', '结束时间']
        const filterVal = ['dormitoryId', 'bannerId', 'sex', 'beginTime', 'endTime']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-dorms'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }}

</script>
